import { defineStore } from 'pinia';
import type { BaseDictInfo, UserInfo } from '@/api/user';
import type MxpToast from '@/mxp-ui/mxp-toast/mxp-toast.vue';
import { isObject } from '@/mxp-ui/mxp-tool/utils/verify';
import type { RewardedVideoAd } from '@/utils/page/adUtil';
export type LaunchQuery = {
  /** 渠道id */
  channelId?: string;
  /** 推广链接ID */
  referralLinkId?: number;
  /** 广告点击id */
  clickid?: string;
  /** 巨量广告项目id */
  projectid?: string;
  /** 巨量广告计划ID */
  promotionid?: string;
  /** 第三方面板ID */
  panelId?: string;
  /**视频号作者ID**/
  wxExportId?: string;
  /**视频号内容ID**/
  wxFinderId?: string;
  /**加热订单ID**/
  wxPromotionId?: string;
  /**推广模式：0-付费（IAP)；1-免费（IAA）；*/
  iaaFlag?: 0 | 1;
  bd_vid?: string;
};

export type WxPlayletCharge = {
  /** 播放器页面唯一ID，可通过此参数获取到PlayletManager实例 */
  playerId: string;
  /** 广告解锁实例 */
  rewardedVideoAd?: RewardedVideoAd;
};

export type WxAdPopupParam = { type: 1 | 2 };

// eslint-disable-next-line no-use-before-define
export type AppStore = ReturnType<typeof useAppStore>;

export const useAppStore = defineStore('app', {
  state: () => {
    return {
      /** 启动参数 */
      launchQuery: {} as LaunchQuery,
      newLaunchQuery: {},
      /** H5是否有交互行为 （用于播放视频，静音） */
      lnteraction: false,
      /** 是否正在登录 */
      isLoginLoading: false,
      /** 是否手动退出登录 (主要用于小程序)  */
      isManualExit: Number(uni.getStorageSync('app_is_manual_exit')) === 1,
      /** Toast 组件实例 */
      mxpToastRef: null as InstanceType<typeof MxpToast> | null,
      /** 业务 token */
      access_token: uni.getStorageSync('app_access_token') || undefined,
      /** 刷新 token */
      refresh_token: uni.getStorageSync('app_refresh_token') || undefined,
      /** 私匙 */
      privateKeyStr: uni.getStorageSync('app_private_keys_str') || undefined,
      /** 用户信息 */
      userInfo: undefined as UserInfo | undefined,
      /** 数据字典信息 */
      baseDictInfo: undefined as BaseDictInfo | undefined,
      /** 是否 AII 1-是 0-不是 */
      isIaaFlag: 0 as 0 | 1,
      /**是否二次弹起广告**/
      twoAdvertFrame: false,
      // #ifdef MP-WEIXIN
      /** 微信短剧充值时传递的信息 */
      wxPlayletCharge: { playerId: '' } as WxPlayletCharge,
      /** 微信打开观看广告弹出框需要的参数 */
      wxAdPopupParam: { type: 1 } as WxAdPopupParam,
      // #endif
      /** 进入页面时间 */
      toDramaPageTime: -1,
    };
  },
  getters: {
    /** 是否登录 */
    loginState(): boolean {
      return Boolean(this.privateKeyStr && this.access_token && this.userInfo && this.baseDictInfo);
    },
  },

  actions: {
    setTwoAdvertFrame(val: boolean) {
      this.twoAdvertFrame = val;
    },
    /** 设置toast */
    setMxpToastRef(toast: InstanceType<typeof MxpToast> | null) {
      this.mxpToastRef = toast;
    },
    /** 设置交互状态 */
    setInteraction() {
      this.lnteraction = true;
    },
    /** 设置业务 token */
    setAccessToken(str: string) {
      this.access_token = str || '';
      uni.setStorageSync('app_access_token', str || '');
    },
    /** 设置刷新 Token */
    setRefreshToken(str: string) {
      this.refresh_token = str || '';
      uni.setStorageSync('app_refresh_token', str || '');
    },

    /** 设置私匙 */
    setPrivateKeyStr(str: string) {
      this.privateKeyStr = str || '';
      uni.setStorageSync('app_private_keys_str', str || '');
    },

    /** 设置登录状态 */
    setIsLoginLoging(bool: boolean) {
      this.isLoginLoading = bool;
    },

    /** 设置是否手动退出登录 */
    setIsManualExit(bool: boolean) {
      this.isManualExit = bool;
      if (bool) {
        uni.setStorageSync('app_is_manual_exit', 1);
      } else {
        uni.removeStorageSync('app_is_manual_exit');
      }
    },

    /** 设置用户信息 */
    setUserInfo(userInfo: UserInfo) {
      this.userInfo = userInfo;
    },
    /** 设置数据字典信息 */
    setBaseDictInfo(dictInfo: BaseDictInfo) {
      this.baseDictInfo = dictInfo;
    },

    /** 更新K币 */
    updateVirtualCoins(virtualCoins: number) {
      if (isObject(this.userInfo) && typeof virtualCoins === 'number') {
        this.userInfo.virtualCoins = virtualCoins;
      }
    },

    /** 更新是否自动解锁下一集 */
    updateIsAutoPay(isAutoPay: 0 | 1) {
      if (isObject(this.userInfo) && typeof isAutoPay === 'number') {
        this.userInfo.isAutoPay = isAutoPay === 1 ? 1 : 0;
      }
    },

    /** 设置是否 aii */
    updateIsIaaFlag(_isIaaFlag: 0 | 1 | null) {
      this.isIaaFlag = _isIaaFlag === 1 ? 1 : 0;
    },

    // #ifdef MP-WEIXIN
    /** 设置微信打开观看广告弹出框需要的参数 */
    updateWxAdPopupParam(wxAdPopupParam: WxAdPopupParam) {
      this.wxAdPopupParam = wxAdPopupParam;
    },
    // #endif
    // #ifdef MP-WEIXIN
    /** 微信短剧充值时传递的信息 */
    setWxPlayletCharge(data: WxPlayletCharge) {
      this.wxPlayletCharge = {
        playerId: data.playerId || this.wxPlayletCharge.playerId || '',
        rewardedVideoAd: data.rewardedVideoAd || this.wxPlayletCharge.rewardedVideoAd || undefined,
      };
    },
    // #endif

    /** 退出登录 */
    logOut() {
      uni.removeStorageSync('app_dict_info');
      uni.removeStorageSync('app_user_info');
      uni.removeStorageSync('app_access_token');
      uni.removeStorageSync('app_refresh_token');
      uni.removeStorageSync('app_private_keys_str');
      this.access_token = undefined;
      this.refresh_token = undefined;
      this.userInfo = undefined;
    },
    /** 存储启动参数 */
    setLaunchQuery(launchQuery: Record<string, unknown>) {
      const referralLinkId = 'referralLinkId' in launchQuery ? launchQuery.referralLinkId : undefined;
      launchQuery.referralLinkId = referralLinkId && !isNaN(Number(referralLinkId)) ? Number(referralLinkId) : undefined;
      this.newLaunchQuery = launchQuery;
      this.launchQuery = launchQuery;
    },

    /** 进入进入短剧页面时间 */
    setToDramaPageTime(teme: number) {
      this.toDramaPageTime = teme;
    },
  },
});
